package 书店销售管理系统;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;

public class VipTypeManagement extends JFrame {
    private static final long serialVersionUID = 1L;
    private JTable table;
    private DefaultTableModel model;

    private final String url = "jdbc:oracle:thin:@localhost:1521:xe";
    private final String user = "HR";
    private final String password = "123456";

    public VipTypeManagement() {
        setTitle("会员类别管理");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(900, 700);
        setLocationRelativeTo(null);
        setLayout(new BorderLayout());

        // 设置背景
        JPanel background = new JPanel() {
            /**
             *
             */
            private static final long serialVersionUID = 1L;

            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                // 绘制半透明粉色背景
                g.setColor(new Color(255, 192, 203, 128));
                g.fillRect(0, 0, getWidth(), getHeight());
            }
        };
        add(background, BorderLayout.CENTER);

        // 创建顶部面板
        JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        topPanel.setOpaque(false); // 设置为透明背景

        // 创建菜单栏
        JMenuBar menuBar = new JMenuBar();
        setJMenuBar(menuBar);

        // 添加下拉菜单
        JMenu dropDownMenu = new JMenu("菜单");
        menuBar.add(dropDownMenu);

        // 添加子菜单：销售信息管理
        JMenuItem salesItem = new JMenuItem("销售信息管理");
        salesItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // 在此添加跳转到“销售信息管理”界面的代码
                new SalesManagement().setVisible(true);
            }
        });
        dropDownMenu.add(salesItem);

        // 添加子菜单：图书信息管理
        JMenuItem bookItem = new JMenuItem("图书信息管理");
        bookItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // 在此添加跳转到“图书信息管理”界面的代码
                new Book().setVisible(true);
            }
        });
        dropDownMenu.add(bookItem);
        
        // 添加子菜单：会员信息管理
        JMenuItem memberItem = new JMenuItem("会员信息管理");
        memberItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // 在此添加跳转到“会员信息管理”界面的代码
                new MemberManagement().setVisible(true);
            }
        });
        dropDownMenu.add(memberItem);
         
        // 添加子菜单：会员类别管理
        JMenuItem memberItem1 = new JMenuItem("用户信息管理");
        memberItem1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // 在此添加跳转到“会员类别管理”界面的代码
                new UserManagement().setVisible(true);
            }
        });
        dropDownMenu.add(memberItem1);

        // 添加子菜单：退出
        JMenuItem exitItem = new JMenuItem("退出");
        exitItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                dispose(); // 关闭窗口
                System.exit(0); // 退出应用程序
            }
        });
        dropDownMenu.add(exitItem);

        // 添加按钮：添加、编辑、删除、查询
        JButton addButton = new JButton("Add");
        addButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                VipTypeDialog dialog = new VipTypeDialog(VipTypeManagement.this, "Add Vip Type", null);
                if (dialog.isOK()) {
                    addVipType(dialog.getData());
                }
            }
        });

        topPanel.add(addButton);

        JButton editButton = new JButton("Edit");
        editButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int row = table.getSelectedRow();
                if (row >= 0) {
                    String vlevel = (String) model.getValueAt(row, 0);
                    Object[] data = { vlevel, model.getValueAt(row, 1), model.getValueAt(row, 2) };
                    VipTypeDialog dialog = new VipTypeDialog(VipTypeManagement.this, "Edit Vip Type", data);
                    if (dialog.isOK()) {
                        editVipType(dialog.getData());
                    }
                } else {
                    JOptionPane.showMessageDialog(VipTypeManagement.this, "请先选择要编辑的会员类别。");
                }
            }
        });

        topPanel.add(editButton);

        JButton deleteButton = new JButton("Delete");
        deleteButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int row = table.getSelectedRow();
                if (row >= 0) {
                    String vlevel = (String) model.getValueAt(row, 0);
                    int result = JOptionPane.showConfirmDialog(VipTypeManagement.this,
                            "你确定要删除类别 \"" + model.getValueAt(row, 1) + "\" 的信息吗？", "删除会员类别",
                            JOptionPane.YES_NO_OPTION);
                    if (result == JOptionPane.YES_OPTION) {
                        deleteVipType(vlevel);
                    }
                } else {
                    JOptionPane.showMessageDialog(VipTypeManagement.this, "请先选择要删除的会员类别。");
                }
            }
        });

        topPanel.add(deleteButton);

        JTextField searchField = new JTextField(20);
        searchField.setHorizontalAlignment(JTextField.CENTER); // 设置文本框居中对齐
        searchField.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                searchVipType(searchField.getText());
            }
        });
        topPanel.add(searchField);

        JButton searchButton = new JButton("Search");
        searchButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                searchVipType(searchField.getText());
            }
        });

        topPanel.add(searchButton);

        // 添加顶部面板
        background.add(topPanel, BorderLayout.NORTH);

        // 创建表格
        String[] columnNames = { "会员等级", "类别名称", "折扣" };
        model = new DefaultTableModel(columnNames, 0);
        table = new JTable(model) {
            private static final long serialVersionUID = 1L;

            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        JScrollPane scrollPane = new JScrollPane(table);
        table.setPreferredScrollableViewportSize(new Dimension(800, 500));

        scrollPane.setOpaque(false);
        scrollPane.getViewport().setOpaque(false);
        background.add(scrollPane, BorderLayout.CENTER);

        refreshTable(); // 刷新表格
        setVisible(true);
    }

    private void refreshTable() {
        model.setRowCount(0); // 清空表格数据
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection conn = DriverManager.getConnection(url, user, password);
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM VIP_TYPE");
            while (rs.next()) {
                String vlevel = rs.getString("VLEVEL");
                String tname = rs.getString("TNAME");
                double discount = rs.getDouble("DISCOUNT");
                model.addRow(new Object[] { vlevel, tname, discount });
            }
            conn.close();
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }

    private void addVipType(Object[] data) {
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection conn = DriverManager.getConnection(url, user, password);
            PreparedStatement pstmt = conn.prepareStatement(
                    "INSERT INTO VIP_TYPE (VLEVEL, TNAME, DISCOUNT) VALUES (?, ?, ?)");
            pstmt.setString(1, data[0].toString());
            pstmt.setString(2, data[1].toString());
            pstmt.setDouble(3, Double.parseDouble(data[2].toString()));
            pstmt.executeUpdate();
            conn.close();
            refreshTable(); // 添加成功后刷新表格
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }

    private void editVipType(Object[] data) {
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection conn = DriverManager.getConnection(url, user, password);
            PreparedStatement pstmt = conn.prepareStatement(
                    "UPDATE VIP_TYPE SET TNAME = ?, DISCOUNT = ? WHERE VLEVEL = ?");
            pstmt.setString(1, data[1].toString());
            pstmt.setDouble(2, Double.parseDouble(data[2].toString()));
            pstmt.setString(3, data[0].toString());

            pstmt.executeUpdate();
            conn.close();
            refreshTable(); // 修改成功后刷新表格
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }

    private void deleteVipType(String vlevel) {
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection conn = DriverManager.getConnection(url, user, password); 
            PreparedStatement pstmt = conn.prepareStatement("DELETE FROM VIP_TYPE WHERE VLEVEL = ?");
            pstmt.setString(1, vlevel); pstmt.executeUpdate(); 
            conn.close(); refreshTable(); 
            // 删除成功后刷新表格 
            } catch (ClassNotFoundException | SQLException e)
        { e.printStackTrace(); } }

                    private void searchVipType(String keyword) {
                        model.setRowCount(0); // 清空表格数据
                        try {
                            Class.forName("oracle.jdbc.driver.OracleDriver");
                            Connection conn = DriverManager.getConnection(url, user, password);
                            Statement stmt = conn.createStatement();
                            ResultSet rs = stmt.executeQuery("SELECT * FROM VIP_TYPE WHERE VLEVEL LIKE '%" + keyword + "%' OR TNAME LIKE '%" + keyword + "%'");
                            while (rs.next()) {
                                String vlevel = rs.getString("VLEVEL");
                                String tname = rs.getString("TNAME");
                                double discount = rs.getDouble("DISCOUNT");
                                model.addRow(new Object[] { vlevel, tname, discount });
                            }
                            conn.close();
                        } catch (ClassNotFoundException | SQLException e) {
                            e.printStackTrace();
                        }
                    }

                    class VipTypeDialog extends JDialog {
                        private static final long serialVersionUID = 1L;
                        private boolean isOK = false;
                        private Object[] data;

                        private JTextField vlevelField, tnameField, discountField;

                        public VipTypeDialog(JFrame parent, String title, Object[] data) {
                            super(parent, title, true); // 设置为模态对话框
                            this.data = data;

                            setSize(400, 200);
                            setLocationRelativeTo(parent);
                            setLayout(new GridLayout(4, 2));

                            JLabel vlevelLabel = new JLabel("会员等级：");
                            add(vlevelLabel);
                            vlevelField = new JTextField();
                            if (data != null) { // 如果是编辑会员类别信息，则将原始数据显示在文本框中
                                vlevelField.setText(data[0].toString());
                                vlevelField.setEnabled(false); // 禁止编辑会员等级
                            }
                            add(vlevelField);

                            JLabel tnameLabel = new JLabel("类别名称：");
                            add(tnameLabel);
                            tnameField = new JTextField();
                            if (data != null) {
                                tnameField.setText(data[1].toString());
                            }
                            add(tnameField);

                            JLabel discountLabel = new JLabel("折扣：");
                            add(discountLabel);
                            discountField = new JTextField();
                            if (data != null) {
                                discountField.setText(data[2].toString());
                            }
                            add(discountField);

                            JButton okButton = new JButton("确定");
                            okButton.addActionListener(new ActionListener() {
                                public void actionPerformed(ActionEvent e) {
                                    if (vlevelField.getText().isEmpty()) {
                                        JOptionPane.showMessageDialog(VipTypeDialog.this, "请填写会员等级。");
                                        return;
                                    }
                                    if (tnameField.getText().isEmpty()) {
                                        JOptionPane.showMessageDialog(VipTypeDialog.this, "请填写类别名称。");
                                        return;
                                    }
                                    if (discountField.getText().isEmpty()) {
                                        JOptionPane.showMessageDialog(VipTypeDialog.this, "请填写折扣。");
                                        return;
                                    }
                                    if (!discountField.getText().matches("^\\d+\\.?\\d*$")) { // 判断折扣是否为数字
                                        JOptionPane.showMessageDialog(VipTypeDialog.this, "折扣必须是数字。");
                                        return;
                                    }

                                    isOK = true;
                                    final Object[] data = new Object[] { 
                                            vlevelField.getText(),
                                            tnameField.getText(),
                                            Double.parseDouble(discountField.getText()) 
                                        };

                                    dispose();
                                }
                            });
                            add(okButton);

                            JButton cancelButton = new JButton("取消");
                            cancelButton.addActionListener(new ActionListener() {
                                public void actionPerformed(ActionEvent e) {
                                    isOK = false;
                                    dispose();
                                }
                            });
                            add(cancelButton);

                            setVisible(true);
                        }

                        public boolean isOK() {
                            return isOK;
                        }

                        public Object[] getData() {
                            return data;
                        }
                    }
                    public static void main(String[] args) {
                        try {
                            for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                                if ("Nimbus".equals(info.getName())) {
                                    UIManager.setLookAndFeel(info.getClassName());
                                    break;
                                }
                            }
                        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException
                                | UnsupportedLookAndFeelException e) {
                            e.printStackTrace();
                        }
                        new VipTypeManagement();
                    }

                    }

                     